package yunwo.cn.yzstation.view.fregment.openorder;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.text.InputFilter;
import android.text.Spanned;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import java.util.List;

import javax.security.auth.callback.Callback;

import yunwo.cn.yzstation.R;
import yunwo.cn.yzstation.adapter.PopupConAdapter;
import yunwo.cn.yzstation.api.IorderView;
import yunwo.cn.yzstation.api.ItotalFeeListen;
import yunwo.cn.yzstation.base.Yzapp;
import yunwo.cn.yzstation.bean.OrderBean.StaTrackingFee;
import yunwo.cn.yzstation.bean.OrderBean.StaTrackingInfo;
import yunwo.cn.yzstation.bean.OrderBean.StaTrackingInfoDetail;
import yunwo.cn.yzstation.bean.PopupBean;
import yunwo.cn.yzstation.bean.YunfeiBean;
import yunwo.cn.yzstation.config.GoodsSP;
import yunwo.cn.yzstation.other.PickDialog;
import yunwo.cn.yzstation.other.ShowAnimationDialogUtil;
import yunwo.cn.yzstation.presenter.OrderFragmentPersenter;
import yunwo.cn.yzstation.utils.SetListViewHeightUtil;
import yunwo.cn.yzstation.utils.StringUtil;
import yunwo.cn.yzstation.utils.UIUtils;
import yunwo.cn.yzstation.view.activity.DetailsActivity;
import yunwo.cn.yzstation.view.activity.OrderActivity;

import static yunwo.cn.yzstation.R.id.sendGoodsTV;

/**
 * Created by lao on 2017/9/5.
 */

public class OrderFragment extends Fragment implements View.OnClickListener, IorderView {

    public boolean printWaybillType = false;
    public boolean printLabelType = false;
    private View rootview;
    public LinearLayout selfLL;
    public LinearLayout sendGoodsLL;
    public TextView selfTV;
    public TextView sendGoodsTV;


    public TextView mBeginOrganName;
    public TextView mEndOrganName;
    public TextView mTransferOrganName;
    public EditText mGoodsSelfNumber;
    public EditText mConsigneeName;
    public EditText mConsigneePhone;
    public EditText mConsigneeAddress;
    public EditText mGoodsNumber;
    public EditText mWeight;
    public EditText mFreight;
    public EditText mRebate;
    public EditText mPremium;
    public EditText mAdvanceTransferCharges;
    public EditText mOtherCharges;
    public EditText mDeliveryCharges;
    public EditText mServiceCharges;
    public TextView mProductName;
    public EditText mVolume;
    public TextView mPackName;
    public EditText mStatement;
    public TextView mPayMeansName;
    public TextView mDeliveryName;
    public EditText mTipTagET;
    public EditText mTipTagNumET;
    public EditText mTicket;
    public EditText mRemarks;

    public double mTotalFee;
    ItotalFeeListen mItotalFee;

    public String mGoodsNumber1;
    public String numberFen;
    public int numberFen1 = 1;
    public int numberFen2 = 1;
    public OrderActivity mActivity;
    public OrderFragmentPersenter mOrderFragmentPersenter;
    private Button mSubmit1;
    private EditText mTipTagET1;
    private StaTrackingInfo mOrderInfoBean;
    private StaTrackingFee mStaTrackingFee;
    private StaTrackingInfoDetail mStaTrackingInfoDetail;
    private LinearLayout mLllistview;
    private ListView mConsigneeLV;
    private TextView mEsc;
    private PopupConAdapter mPopupConAdapter;
    private TextView mNext;


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        rootview = inflater.inflate(R.layout.order_fragment, container, false);

        return rootview;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mActivity = (OrderActivity) getActivity();
        mOrderInfoBean = mActivity.getOrderInfoBean();
        mStaTrackingFee = mActivity.getStaTrackingFee();
        mStaTrackingInfoDetail = mActivity.getStaTrackingInfoDetail();
        initView();
        mOrderFragmentPersenter = new OrderFragmentPersenter(mActivity, this, this, mOrderInfoBean, mStaTrackingFee, mStaTrackingInfoDetail);
        mOrderFragmentPersenter.getEndOrgan();
        setWatcherListener(getActivity(),mGoodsNumber);
        setWatcherListener(getActivity(), mVolume);
        setWatcherListener(getActivity(), mWeight);
        setWatcherListener(getActivity(), mFreight);
        setWatcherListener(getActivity(), mPremium);
        setWatcherListener(getActivity(), mTipTagET);
        setWatcherListener(getActivity(), mOtherCharges);
        setWatcherListener(getActivity(), mServiceCharges);
        setWatcherListener(getActivity(), mDeliveryCharges);
        setWatcherListener(getActivity(), mGoodsSelfNumber);
        setWatcherListener(getActivity(), mAdvanceTransferCharges);
        setWatcherListener(getActivity(), mConsigneeName);
        setWatcherListener(getActivity(), mConsigneePhone);
        setWatcherListener(getActivity(), mConsigneeAddress);
        cursorInitData();
    }

    private void cursorInitData() {
        mConsigneeName.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean b) {
                if (b) {}else {
                    mLllistview.setVisibility(View.GONE);
                }
            }
        });
        mConsigneePhone.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean b) {
                if (b) {}else {
                    mLllistview.setVisibility(View.GONE);
                }
            }
        });
        mConsigneeAddress.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean b) {
                if (b) {}else {
                    mLllistview.setVisibility(View.GONE);
                }
            }
        });
    }

    private void initView() {
        mEsc = (TextView) rootview.findViewById(R.id.esc);
        mConsigneeLV = (ListView) rootview.findViewById(R.id.mconsigneeLV);
        mLllistview = (LinearLayout) rootview.findViewById(R.id.lllistview);
        mNext = (TextView) rootview.findViewById(R.id.next);
        mTipTagET = (EditText) rootview.findViewById(R.id.tipTagET);
        mTipTagNumET = (EditText) rootview.findViewById(R.id.tipTagNumET);
        mTipTagNumET.setEnabled(false);
        mTicket = (EditText) rootview.findViewById(R.id.ticket);
        mSubmit1 = (Button) rootview.findViewById(R.id.submit1);
        mWeight = (EditText) rootview.findViewById(R.id.weight);  //重量
        mVolume = (EditText) rootview.findViewById(R.id.volume); //体积
        mRebate = (EditText) rootview.findViewById(R.id.rebate);  //回扣
        mRemarks = (EditText) rootview.findViewById(R.id.remarks);  //备注
        mFreight = (EditText) rootview.findViewById(R.id.freight);   //运费
        mPremium = (EditText) rootview.findViewById(R.id.premium);   //保费
        mPackName = (TextView) rootview.findViewById(R.id.packName);  //包装
        mEndOrganName = (TextView) rootview.findViewById(R.id.endOgranName);  //目的站
        mProductName = (TextView) rootview.findViewById(R.id.productName);  //品名
        mGoodsNumber = (EditText) rootview.findViewById(R.id.goodsNumber);   //件数
        mOtherCharges = (EditText) rootview.findViewById(R.id.otherCharges);   //其他费
        mPayMeansName = (TextView) rootview.findViewById(R.id.payMeansName);   //付款方式
        mDeliveryName = (TextView) rootview.findViewById(R.id.deliveryName);  //交接方式
        mConsigneeName = (EditText) rootview.findViewById(R.id.consigneeName);   //收货人
        mConsigneePhone = (EditText) rootview.findViewById(R.id.consigneePhone);   //收货人电话
        mServiceCharges = (EditText) rootview.findViewById(R.id.serviceCharges);   //服务费
        mBeginOrganName = (TextView) rootview.findViewById(R.id.beginOrganName);   //始发站
        mGoodsSelfNumber = (EditText) rootview.findViewById(R.id.goodsSelfNumber);  //自编号
        mDeliveryCharges = (EditText) rootview.findViewById(R.id.deliveryCharges);   //送货费
        mConsigneeAddress = (EditText) rootview.findViewById(R.id.consigneeAddress);   //收货人地址
        mTransferOrganName = (TextView) rootview.findViewById(R.id.transferOrganName);  //中转站
        mAdvanceTransferCharges = (EditText) rootview.findViewById(R.id.advanceTransferCharges); //垫中转费

        mPackName.setText(Yzapp.getInstance().getPackingname());
        mProductName.setText(Yzapp.getInstance().getproductName());
//        Toast.makeText(getContext(), "品名" + Yzapp.getInstance().getPackingname() + "包装" + Yzapp.getInstance().getproductName(), Toast.LENGTH_SHORT).show();

        selfTV = (TextView) rootview.findViewById(R.id.selfTV);
        selfLL = (LinearLayout) rootview.findViewById(R.id.selfLL);
        sendGoodsTV = (TextView) rootview.findViewById(R.id.sendGoodsTV);
        sendGoodsLL = (LinearLayout) rootview.findViewById(R.id.sendGoodsLL);
        mNext.setOnClickListener(this);
        mEsc.setOnClickListener(this);
        selfLL.setOnClickListener(this);
        mSubmit1.setOnClickListener(this);
        mPackName.setOnClickListener(this);
        sendGoodsLL.setOnClickListener(this);
        mProductName.setOnClickListener(this);
        mPayMeansName.setOnClickListener(this);
        mDeliveryName.setOnClickListener(this);
        mEndOrganName.setOnClickListener(this);
        mTransferOrganName.setOnClickListener(this);
        mBeginOrganName.setText(Yzapp.getInstance().getgetBeginOrgName());
    }

    public void submit() {
        mOrderFragmentPersenter.setKeyvalue();
    }


    private void setWatcherListener(final Activity activity, final EditText editText) {
        TextWatcher watchContent = new TextWatcher() {


            private boolean isChanged = false;
            private CharSequence temp;

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

                switch (editText.getId()) {
                    case R.id.goodsNumber:
                        if (s.toString().contains(".")) {
                            editText.setText("1");
                            Toast.makeText(getContext(), "件数请出入整数", Toast.LENGTH_SHORT).show();
                            return;
                        }
                        mTipTagNumET.setText(s.toString().trim());
                        break;
                }

            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.toString().contains(".") && s.toString().length() == 1){
                    editText.setText("0.");
                    editText.setSelection(editText.length());
                    return;
                }
                switch (editText.getId()) {
                    case R.id.consigneeName:
                        String trim = mConsigneeName.getText().toString().trim();
                        if (!StringUtil.isEmpty(trim)) {
                            String consigneeName = GoodsSP.getInstance().getGoodsShare().getString("consigneeName", "");
                            if (!trim.equals(consigneeName)) {
                                mOrderFragmentPersenter.requestPopupCon("1", trim);
                            } else {
                                mLllistview.setVisibility(View.GONE);
                            }
                        } else {
                            mLllistview.setVisibility(View.GONE);
                        }
                        break;
                    case R.id.consigneePhone:


                        String trim1 = mConsigneePhone.getText().toString().trim();
                        if (!StringUtil.isEmpty(trim1)) {
                            String consigneeName = GoodsSP.getInstance().getGoodsShare().getString("consigneePhone", "");
                            if (!trim1.equals(consigneeName)) {
                                mOrderFragmentPersenter.requestPopupCon("2", trim1);
                            } else {
                                mLllistview.setVisibility(View.GONE);
                            }
                        } else {
                            mLllistview.setVisibility(View.GONE);
                        }

                        break;
                    case R.id.consigneeAddress:
                      /*  String consigneeAddress = s.toString();
                        if (!consigneeAddress.equals("")) {
                            mOrderFragmentPersenter.requestPopupCon("3",consigneeAddress);
                        }*/

                        String trim2 = mConsigneeAddress.getText().toString().trim();
                        if (!StringUtil.isEmpty(trim2)) {
                            String consigneeAddress = GoodsSP.getInstance().getGoodsShare().getString("consigneeAddress", "");
                            if (!trim2.equals(consigneeAddress)) {
                                mOrderFragmentPersenter.requestPopupCon("3", trim2);
                            } else {
                                mLllistview.setVisibility(View.GONE);
                            }
                        } else {
                            mLllistview.setVisibility(View.GONE);
                        }
                        break;
                    case R.id.tipTagET:
                        try {
                            int tipTag = Integer.parseInt(mTipTagET.getText().toString().trim());
                            int Number = Integer.parseInt(mGoodsNumber.getText().toString().trim());
                            if (tipTag > Number) {
                                Toast.makeText(getContext(), "标签号不能大于总件数", Toast.LENGTH_SHORT).show();
                                mTipTagET.setText("1");
                            } else {

                        /*if (tipTag == 1) {
                            tipTag = 0;
                        }*/
                                if (tipTag == Number) {
                                    mTipTagNumET.setText(1 + "");
                                    return;
                                }

                                int i = Number - (tipTag - 1);
                                mTipTagNumET.setText(i + "");
                            }
                        } catch (Exception e) {
                        }

                        break;
                    case R.id.goodsSelfNumber:
                    /*    GoodsSP.getInstance().setGoodsSelfNumber(s.toString());
                        GoodsSP.getInstance().getEdit().commit();*/
                        break;
                    case R.id.freight:  // 运费
                        countTotalFee();
                        if (!StringUtil.isEmpty(mFreight.getText().toString().trim())) {
                            mOrderFragmentPersenter.getXiaoFei(s.toString());
                        }
                        break;
                    case R.id.premium://保费
                        countTotalFee();
                        break;
                    case R.id.advanceTransferCharges://垫中转
                        countTotalFee();
                        break;
                    case R.id.otherCharges://其他费
                        countTotalFee();
                        break;
                    case R.id.deliveryCharges://送货费
                        countTotalFee();
                        break;
                    case R.id.serviceCharges://服务费
                        countTotalFee();
                        break;
                    case R.id.weight:
                        if (!GoodsSP.getInstance().getGoodsShare().getString("endOrganId", "").equals("")) {
                            if (!StringUtil.isEmpty(mWeight.getText().toString().trim())) {
                                mOrderFragmentPersenter.getYunFei(s.toString(), "1");
                            }
                        }
                        break;
                    case R.id.volume:
                        if (!GoodsSP.getInstance().getGoodsShare().getString("endOrganId", "").equals("")) {
                            if (!StringUtil.isEmpty(mVolume.getText().toString().trim())) {
                                mOrderFragmentPersenter.getYunFei(s.toString(), "2");
                            }
                        }
                        break;
                }
            }
        };
        editText.addTextChangedListener(watchContent);
    }


    //计费
    public void countTotalFee() {

        //运费 保费
        String freight = mFreight.getText().toString().trim();
        String premium = mPremium.getText().toString().trim();
        String Servicefee = mServiceCharges.getText().toString().trim();
        if (StringUtil.isEmpty(Servicefee)) {
            Servicefee = "0.00";
        }
        if (StringUtil.isEmpty(freight)) {
            freight = "0.00";
        }
        if (StringUtil.isEmpty(premium)) {
            premium = "0.00";
        }
        double ServicefeeET = Double.parseDouble(Servicefee);
        double freightET = Double.parseDouble(freight);
        double premiumET = Double.parseDouble(premium);

        // 送货费 垫中转费  其他费
        String deliveryCharges = mDeliveryCharges.getText().toString().trim();
        String transferFee = mAdvanceTransferCharges.getText().toString().trim();
        String mOtherFee = mOtherCharges.getText().toString().trim();

        if (StringUtil.isEmpty(deliveryCharges)) {
            deliveryCharges = "0.00";
        }
        if (StringUtil.isEmpty(transferFee)) {
            transferFee = "0.00";
        }
        if (StringUtil.isEmpty(mOtherFee)) {
            mOtherFee = "0.00";
        }
        double deliveryChargesET = Double.parseDouble(deliveryCharges);
        double transferFeeET = Double.parseDouble(transferFee);
        double mOtherFeeET = Double.parseDouble(mOtherFee);


        mTotalFee = freightET + premiumET + ServicefeeET +
                deliveryChargesET + transferFeeET + mOtherFeeET;
//        Toast.makeText(getContext(), mTotalFee + "", Toast.LENGTH_SHORT).show();

        mItotalFee.totalFee(mTotalFee);

    }


    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.next:
                mActivity.mViewPager.setCurrentItem(1);
                break;

            case R.id.esc:
                mLllistview.setVisibility(View.GONE);
                break;
            case R.id.transferOrganName:
                mOrderFragmentPersenter.screening("1");  //中转站
                break;
            case R.id.endOgranName:
                mOrderFragmentPersenter.screening("2");   //目的站
                break;
            case R.id.productName:
                mOrderFragmentPersenter.screening("3");  //品名
                break;
            case R.id.packName:
                mOrderFragmentPersenter.screening("4");  //包装
                break;
            case R.id.payMeansName:
                PickDialog selectPayTypeDialog2 = ShowAnimationDialogUtil.showDialog(
                        getActivity(), R.layout.activity_pay_type_dialog);
                mOrderFragmentPersenter.initPayTypeDialogView(selectPayTypeDialog2, mOrderFragmentPersenter.mDictNamelist,
                        mOrderFragmentPersenter.mDictNameMap, mPayMeansName, true);
                break;
            case R.id.deliveryName:
                PickDialog selectPayTypeDialog = ShowAnimationDialogUtil.showDialog(
                        getActivity(), R.layout.activity_pay_type_dialog);
                mOrderFragmentPersenter.initPayTypeDialogView(selectPayTypeDialog, mOrderFragmentPersenter.mJiaojielist,
                        mOrderFragmentPersenter.mJiaojiemap, mDeliveryName, false);
                break;
            case R.id.submit1:
                submit();
                break;
            case R.id.sendGoodsLL:

                if (printLabelType) {
                    printLabelType = false;
                    sendGoodsTV.setBackgroundResource(R.drawable.click_icon);
                } else {
                    printLabelType = true;
                    sendGoodsTV.setBackgroundResource(R.drawable.checkbox_selector);
                }
                break;
            case R.id.selfLL:
                if (printWaybillType) {
                    printWaybillType = false;
                    selfTV.setBackgroundResource(R.drawable.click_icon);
                } else {
                    printWaybillType = true;
                    selfTV.setBackgroundResource(R.drawable.checkbox_selector);
                }
                break;
        }
    }

    public void setLisent(ItotalFeeListen mItotalFee) {
        this.mItotalFee = mItotalFee;
    }

    @Override
    public void getXiaoFeiSuccess(int data) {
        if (data != 0) {
            mRebate.setText(data + "");
        }
    }

    @Override
    public void getYunFeiSuccsee(YunfeiBean response) {
        if (response.getData() != 0) {
            mFreight.setText(response.getData() + "");
        }
    }

    @Override
    public void OpenOrderSuccess(String type, StaTrackingInfo orderInfoBean) {
        Toast.makeText(getContext(), "开单成功", Toast.LENGTH_SHORT).show();
        mActivity.finish();
    }

    @Override
    public void OpenOrderfailure(int code, String msg) {
        Toast.makeText(getContext(), "开单失败" + code + msg, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void requestPopupConSuccess(List<PopupBean.DataBean> popupBean) {
        setPopup(popupBean);
    }

    private void setPopup(final List<PopupBean.DataBean> popupBean) {
        if (popupBean.size() > 0) {
            mLllistview.setVisibility(View.VISIBLE);
            mPopupConAdapter = new PopupConAdapter(popupBean, getContext());
            mConsigneeLV.setAdapter(mPopupConAdapter);
            SetListViewHeightUtil.setListViewHeightBasedOnChildren(mConsigneeLV);
            mConsigneeLV.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                    PopupBean.DataBean dataBean = popupBean.get(i);
                    if (dataBean != null) {
                        GoodsSP.getInstance().setConsigneeName(dataBean.getName());
                        GoodsSP.getInstance().setConsigneePhone(dataBean.getPhone());
                        GoodsSP.getInstance().setConsigneeAddress(dataBean.getAddress());
                        GoodsSP.getInstance().getEdit().commit();
                        mStaTrackingInfoDetail.setConsigneeId(dataBean.getCustomerId());
                        mConsigneeName.setText(dataBean.getName());
                        mConsigneePhone.setText(dataBean.getPhone());
                        mConsigneeAddress.setText(dataBean.getAddress());
                        mLllistview.setVisibility(View.GONE);
                    }
                }
            });
        } else {
            mLllistview.setVisibility(View.GONE);
        }

    }
}
